package hui.zhang.bos.web.action;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import hui.zhang.bos.utils.BaseAction;
import hui.zhang.commons.CommonUtils;
import hui.zhang.constant.Constants;
import hui.zhang.crm.domain.Customer;
import hui.zhang.mail.Mail;
import hui.zhang.mail.MailUtils;

@Controller
@ParentPackage("struts-default")
@Namespace("/")
@Scope("prototype")
@SuppressWarnings("all")
public class CustomerAction extends BaseAction<Customer> {

	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	// 属性封装checkcode
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	/**
	 * 注册发短信验证码
	 */
	@Action(value = "customer_sendSms")
	public void sendSms() {
		// Integer code = SmsUtils.sendSms(model.getTelephone());
		// Integer code = 123456;
		// if (code != null) {
		// ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(),
		// code);
		// System.out.println("发送成功！验证码是：" + code);
		// } else {
		// throw new RuntimeException("短信发送失败...");
		// }

		// 生成验证码
		final int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), mobile_code);

		// 调用MQ服务，发送一条消息
		jmsTemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setInt("mobile_code", mobile_code);
				return mapMessage;
			}
		});
		System.out.println("回调验证码" + ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone()));

	}

	/**
	 * 注册
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "customer_regist", results = {
			@Result(name = "success", location = "/signup-success.html", type = "redirect"),
			@Result(name = "input", type = "redirect", location = "/signup.html") })
	public String regist() throws Exception {
		Integer code = (Integer) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if (code == null || !("" + code).equals(checkcode)) {
			System.out.println("短信验证失败...");
			return INPUT;
		}
		WebClient.create("http://localhost:8081/crm_management/services/customerService/customer")
				.type(MediaType.APPLICATION_JSON).post(model);
		System.out.println("客户注册成功...");

		// 邮箱发送激活码
		Properties props = new Properties();
		props.load(this.getClass().getClassLoader().getResourceAsStream("email.properties"));
		String host = props.getProperty("host");
		String uname = props.getProperty("uname");
		String pwd = props.getProperty("pwd");
		String from = props.getProperty("from");
		String subject = props.getProperty("subject");
		String content = props.getProperty("content");
		String activation = CommonUtils.uuid() + CommonUtils.uuid();
		content = MessageFormat.format(content, model.getTelephone(), activation);
		javax.mail.Session createSession = MailUtils.createSession(host, uname, pwd);
		Mail mail = new Mail(from, model.getEmail(), subject, content);
		MailUtils.send(createSession, mail);

		// 24小时激活，否则过期
		redisTemplate.opsForValue().set(model.getTelephone(), activation, 24, TimeUnit.HOURS);

		return SUCCESS;
	}

	/**
	 * 激活
	 * 
	 * @throws IOException
	 */
	@Action(value = "customer_active")
	public void active() throws IOException {
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		String tel = ServletActionContext.getRequest().getParameter("telephone");
		String code = ServletActionContext.getRequest().getParameter("code");
		String vcode = redisTemplate.opsForValue().get(tel);
		if (vcode == null || !vcode.equals(code)) {
			ServletActionContext.getResponse().getWriter()
					.println("<h2>邮件激活失败！激活码已经过期！！！请重新绑定<a href='http://localhost:8082/bos_fore'>点击这里去往首页</a></h2>");
		} else {
			// 激活码正确 webservice验证是否已经激活
			Customer customer = WebClient
					.create("http://localhost:8081/crm_management/services/customerService/customer/telephone/" + tel)
					.type(MediaType.APPLICATION_JSON).get(Customer.class);
			// 没激活
			if (customer.getType() == null || customer.getType() != 1) {
				WebClient.create(
						"http://localhost:8081/crm_management/services/customerService/customer/updatetype/" + tel)
						.type(MediaType.APPLICATION_JSON).put(tel);
				ServletActionContext.getResponse().getWriter()
						.println("<h2>邮件激活成功！<a href='http://localhost:8082/bos_fore'>点击这里去往首页登录</a></h2>");
			} else {
				ServletActionContext.getResponse().getWriter().println("<h2>已经激活过了，请不要乱搞！</h2>");
			}

			redisTemplate.delete(tel);

		}
	}

	@Action(value = "customer_login", results = {
			@Result(name = "success", location = "/index.html#/myhome", type = "redirect"),
			@Result(name = "login", location = "/login.html", type = "redirect") })
	public String login() {
		// webservice调用crm_management验证登录
		Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL + 
				"/crm_management/services/customerService/customer/login?telephone="
				+ model.getTelephone() + "&password=" + model.getPassword())
				.accept(MediaType.APPLICATION_JSON).get(Customer.class);
		if (customer!=null) {
			//保存登录状态
			ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
			System.out.println("登录成功！");
			return SUCCESS;
		} else {
			return LOGIN;
		}
	}

}
